import { BlockInputEvents, Color, Component, game, Graphics, UITransform, view, _decorator } from 'cc'
const { ccclass } = _decorator
/** 用来做场景间的淡入、淡出的过度动画 */

const SCREEN_WIDTH = view.getVisibleSize().width // 屏幕宽度
const SCREEN_HEIGHT = view.getVisibleSize().height // 屏幕高度

export const DEFAULT_FADE_DURATION = 200 // 默认过渡时间间隔

/** 过渡状态 */
enum FadeStatus {
  IDLE,
  FADE_IN,
  FADE_OUT,
}

@ccclass('DrawMgr')
export class DrawMgr extends Component {
  oldTime: number = 0 // 旧时间
  duration: number = DEFAULT_FADE_DURATION // 过度时间间隔
  fadeStatus: FadeStatus = FadeStatus.IDLE // 过度状态
  // 允许其他代码通过 await 或 .then() 方式等待淡入淡出动画完成后再执行后续操作。
  fadeResolve: (value: PromiseLike<null>) => void
  faderNode: Node
  ctx: Graphics // 画笔
  block: BlockInputEvents

  init() {
    this.ctx = this.addComponent(Graphics)

    // 存在蒙版时，组织用户的点击输入
    this.block = this.addComponent(BlockInputEvents)
    const transform = this.getComponent(UITransform)
    transform.setAnchorPoint(0.5, 0.5)
    transform.setContentSize(SCREEN_WIDTH, SCREEN_HEIGHT)

    this.setAlpha(1)
  }

  private setAlpha(percent: number) {
    this.ctx.clear()
    this.ctx.rect(0, 0, SCREEN_WIDTH * 100, SCREEN_HEIGHT * 100)
    this.ctx.fillColor = new Color(0, 0, 0, 255 * percent)
    this.ctx.fill()

    this.block.enabled = percent === 1 // 全黑时生效
  }

  update() {
    const fadePercent = (game.totalTime - this.oldTime) / this.duration // 计算当前百分比
    switch (this.fadeStatus) {
      case FadeStatus.FADE_IN:
        if (fadePercent < 1) {
          this.setAlpha(fadePercent)
        } else {
          this.fadeStatus = FadeStatus.IDLE
          this.setAlpha(1)
          this.fadeResolve(null)
        }
        break
      case FadeStatus.FADE_OUT:
        if (fadePercent < 1) {
          this.setAlpha(1 - fadePercent)
        } else {
          this.fadeStatus = FadeStatus.IDLE
          this.setAlpha(0)
          this.fadeResolve(null)
        }
        break
      default:
        break
    }
  }

  /** 淡入 */
  fadeIn(duration: number = DEFAULT_FADE_DURATION) {
    this.setAlpha(0) // 设置蒙层透明度为0
    this.duration = duration // 设置过度时间间隔
    this.fadeStatus = FadeStatus.FADE_IN // 设置过度状态为淡入
    this.oldTime = game.totalTime // 记录当前时间
    // 创建一个 Promise 对象，并返回给调用者
    return new Promise(resolve => {
      this.fadeResolve = resolve
    })
  }

  /** 淡出 */
  fadeOut(duration: number = DEFAULT_FADE_DURATION) {
    this.setAlpha(1)
    this.duration = duration
    this.fadeStatus = FadeStatus.FADE_OUT
    this.oldTime = game.totalTime
    return new Promise(resolve => {
      this.fadeResolve = resolve
    })
  }

  // mask() {
  //   this.setAlpha(1)
  //   return new Promise(resolve => {
  //     setTimeout(resolve, DEFAULT_FADE_DURATION)
  //   })
  // }
}
